package watcher

import (
	"fmt"
	"os"

	"github.com/micro-plat/lib4go/types"
)

// startOffsetWriter 启动一个goroutine来处理定时写入偏移量
func (w *FileWatcher) startOffsetWriter() {
	defer w.ticker.Stop()
	for {
		select {
		case <-w.ticker.C:
			w.writeOffset() // 定时写入偏移量
		case <-w.watcher.Errors: // 当监控器关闭时，退出
			return
		}
	}
}

// writeOffset 将当前偏移量写入文件
func (w *FileWatcher) writeOffset() {
	w.mu.Lock()
	defer w.mu.Unlock()
	diff := w.offset - w.savedOffset
	diffLine := w.lineCount - w.savedLinecoount
	if !w.needSaveOffset || diff == 0 {
		return
	}
	w.savedOffset = w.offset
	w.log.Infof("已读取: %d行，%d", diffLine, w.savedOffset)
	if err := os.WriteFile(w.offsetPath, []byte(fmt.Sprintf("%d", w.savedOffset)), 0644); err != nil {
		w.log.Errorf("写入偏移量出错: %v", err)
	}
}

// LoadOffsetFile 加载偏移量文件
func (w *FileWatcher) loadOffsetFile() (string, int64) {

	// 尝试打开偏移量文件，如果不存在则创建并初始化为0
	path := "./nginx-exporter" + offsetFileName
	if _, err := os.Stat(path); os.IsNotExist(err) {
		return path, 0
	}

	content, err := os.ReadFile(path)
	if err != nil {
		return path, 0
	}

	return path, types.GetInt64(string(content))

}
